package cn.just.controller;

import cn.just.entity.User;
import cn.just.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author wujiaming
 */
@WebServlet(name = "LoginServlet",value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        String rem = request.getParameter("rem");
//        System.out.println("rem:" + rem);

        UserService userService = new UserService();
        User dbUser = userService.findUserById(name,pwd);


        if(dbUser ==null){
            response.sendRedirect("ShowLoginServlet");
        }else{
            //记住用户名和密码
            if(rem !=null){
                Cookie c1 = new Cookie("name",name);
                Cookie c2 = new Cookie("pwd", pwd);
                response.addCookie(c1);
                response.addCookie(c2);
            }
            //通过session实现自动登录
            //获取session对象(如果是第一次访问也作为创建session对象)
            HttpSession session = request.getSession();
//            System.out.println(session.getId());
            //把登录成功的信息保存到session中
            session.setAttribute("user",dbUser);
            //登录成功，重定向
            response.sendRedirect("HomeServlet");
        }
    }


}
